package com.kcsoft.controller;

import com.kcsoft.pojo.Assistant;
import com.kcsoft.pojo.PageBean;
import com.kcsoft.pojo.Result;
import com.kcsoft.service.ChatService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.util.List;


@RestController
@RequestMapping("/chat")
public class ChatController {

    @Autowired
    private ChatService chatService;

    //创建会话
    @PostMapping("/sessions")
    public Result<String> createSession(String chatName, String assistantId, String type) {

        String sessionId = chatService.genSession(chatName, assistantId, type);

        if (!sessionId.equals("")){
            chatService.saveSession(sessionId, chatName, assistantId, type);
            return Result.success(sessionId);
        }

        return Result.error("创建会话失败");
    }

    @GetMapping("/assistants")
    public Result<List<Assistant>> list(){

        List<Assistant> assistants = chatService.list();

        return Result.success(assistants);

    }

    @PostMapping ("/msg")
    public Flux<String> getAnswer(String sessionId, String question){
        String assistantId = chatService.findBySession(sessionId);
        return chatService.getAnswer(sessionId, question, assistantId);
    }

    @GetMapping("/history")
    public String getHistory(String sessionId) throws IOException, InterruptedException {
        return chatService.getHistory(sessionId);
    }

    @DeleteMapping("/delete")
    public Result<String> deleteSession(String sessionId){
        chatService.deleteSession(sessionId);
        return Result.success("删除会话成功");
    }
}